<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <!-- 绑定添加函数 -->
      <button @click="addModifyBtn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <!-- 需求1: 铺设页面 -->
        <tr v-for="(obj, index) in studentList" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ obj.uname }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.sex }}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="editFn(obj.uname, obj.age, obj.sex)">编辑</button>
          </td>
        </tr>
        <!-- 没有数据时展示 -->
        <tr style="text-align: center" v-show="studentList.length === 0">
          <td colspan="5">暂无数据</td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      studentList: [
        {
          uname: "张三",
          age: 18,
          sex: "男",
        },
        {
          uname: "李四",
          age: 20,
          sex: "女",
        },
      ],
      uname: "",
      age: 0,
      sex: "",
      flag: false,
    };
  },
  methods: {
    // 添加和修改
    addModifyBtn() {
      if (!this.flag) {
        if (
          this.uname.trim().length === 0 ||
          toString(this.age).trim().length === 0 ||
          this.sex.trim().length === 0
        ) {
          return alert("输入不合法，请输入完整信息");
        }
        alert("确定要添加新数据吗？");
        let obj = {};
        obj.uname = this.uname;
        obj.age = this.age;
        obj.sex = this.sex;
        // console.log(obj);
        this.studentList.push(obj);
        this.uname = "";
        this.age = "";
        this.sex = "";
      }
      if (this.flag) {
        // alert('确保数据已重新编辑')
        alert("确定要添加修改后的数据吗？");
        let obj = {};
        obj.uname = this.uname;
        obj.age = this.age;
        obj.sex = this.sex;
        // console.log(obj);
        this.studentList.push(obj);
        this.uname = "";
        this.age = "";
        this.sex = "";
        this.flag = false;
      }
    },
    // 编辑
    editFn(a, b, c) {
      // console.log(ind);
      this.uname = a;
      this.age = b;
      this.sex = c;
      this.flag = true;
    },
    // 删除
    delFn(ind) {
      this.studentList.splice(ind, 1);
    },
  },
};
</script>
<style scoped>
</style>